var stompClient = null;

function connect() {
    // websocket的连接地址，此值等于WebSocketMessageBrokerConfigurer中registry.addEndpoint("/websocket-simple").withSockJS()配置的地址
    var socket = new SockJS('/portfolio');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function(frame) {
        setConnected(true);
        showResponse('Connected: ' + frame);
        stompClient.subscribe('/topic/greeting', function(respnose2){
            showResponse(JSON.stringify(JSON.parse(respnose2.body)));
        });
    });
}

function greeting() {
    showResponse('greeting start');
    stompClient.send("/app/greeting", {}, JSON.stringify({
        'content': $("#name").val()
    }));
}

function sendGreeting() {
    showResponse('sendGreeting start');
    stompClient.send("/app/sendGreeting", {}, JSON.stringify({
        'content': $("#name").val()
    }));
}

function throwException() {
    showResponse('throwException start');
    stompClient.send("/app/exception", {}, JSON.stringify({
        'content': $("#name").val()
    }));
}

function sendSimpMsg() {
    showResponse('sendSimpMsg start');
    stompClient.send("/topic/greeting", {}, JSON.stringify({
        'content': $("#name").val()
    }));
}

function disconnect() {
    if (stompClient != null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    var name = $('#name').val();
    // 客户端消息发送的目的：服务端使用BroadcastCtl中@MessageMapping("/receive")注解的方法来处理发送过来的消息
    stompClient.send("/receive", {}, JSON.stringify({ 'name': name }));
}

function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
    $('#response').html();
}

function showResponse(message) {
    var response = $("#response");
    response.html(message + "<br\>" + response.html());
}